<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="60%" @ok="handleSubmit" :closeFunc="beforeClose">
    <a-row>
      <a-col span="24">
        <a-steps :current="current" class="steps-flow">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" :description="item.description" />
        </a-steps>
        <div class="steps-content scbz_box">
          <a-col span="12" style="margin: auto;" v-if="current == 0">
            <div class="lb_item">
              <div class="lb_tit">种植计划：<span>*</span></div>
              <div class="kuang">
                <!-- <a-select ref="select" v-model:value="formData.growPlanId" @change="handleChange1" placeholder="请选择种植计划">
                  <a-select-option :value="item.value" v-for="(item,index) in options1"
                    :key="index">{{item.label}}</a-select-option>
                </a-select> -->
                <JDictSelectTag v-model:value="formData.growPlanId" placeholder="请选择种植计划" @change="handleChange1" dictCode="t_grow_plan,id,id"/>
              </div>
              <div class="wxts" v-if="errmsg.indexOf('growPlanId') > -1">请选择种植计划!</div>
            </div>
            <!-- <div class="lb_item" v-if="plan.productNo_dictText">
              <div class="lb_tit">农产品：</div>
              <div class="kuang">
                <span style="line-height: 40px;padding: 0 11px;color: #555;">{{plan.productNo_dictText}}</span>
              </div>
            </div> -->
            <div class="lb_item">
              <div class="lb_tit">农产品：</div>
              <div class="kuang">
                <a-select placeholder="请选择农产品" v-model:value="formData.growPlanProductPlotId" @change="handleChange3">
                  <a-select-option :value="item.id" v-for="(item,index) in planList"
                    :key="index">{{item.productNo_dictText}}-{{item.plotId_dictText}}</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">农事操作：<span>*</span></div>
              <div class="kuang" style="position: relative;">
                <!-- <a-select ref="select" v-model:value="formData.productionOperation" @change="handleChange2">
                  <a-select-option :value="item.key" v-for="(item,index) in options2"
                    :key="index">{{item.title}}</a-select-option>
                </a-select> -->
                <!-- <JDictSelectTag v-model:value="formData.productionOperation" placeholder="请选择农事操作"
                  dictCode="t_classification,name,id,associate_id like '%1691638504639508482%' and pid = '1689815136974086145'"
                  pidField="pid"
                  pidValue="1689815136974086145"
                  hasChildField="has_child"/> -->
                  <ApiSelect v-model:value="formData.productionOperation" @change="handleChange2" placeholder="请选择农事操作" resultField="records" labelField="name" valueField="id" :api="getOperate"></ApiSelect>
                  <a-button type="primary" style="margin-left: 8px;position: absolute;height: 100%" @click="addOperation">新增操作</a-button>
              </div>
              <div class="wxts" v-if="errmsg.indexOf('productionOperation') > -1">请选择农事操作!</div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">作业内容：</div>
              <div class="kuang kuang1">
                <a-textarea style="height: 100%;" v-model:value="formData.operationContent" placeholder="请输入作业内容" allowClear />
              </div>
            </div>
          </a-col>
          <a-col span="12" style="margin: auto;" v-if="current == 1">
            <div class="lb_item">
              <div class="lb_tit">投入品：</div>
              <div class="kuang">
                <!-- <a-select ref="select" v-model:value="formData.input" style="width: 120px"
                  @change="handleChange3">
                  <a-select-option :value="item.value" v-for="(item,index) in options3"
                    :key="index">{{item.label}}</a-select-option>
                </a-select> -->
                <JSelectMultiple v-model:value="formData.input" placeholder="请选择投入品" dictCode="t_inputs,name,id" @change="changeInput"></JSelectMultiple>
              </div>
            </div>
            <div class="lb_item" v-if="formData.input">
              <div class="lb_tit">投入品用量：</div>
              <div class="kuang sousuo">
                <a-input v-model:value="formData.usageAndDosage" placeholder="请输入投入品用量" />
              </div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">作业要求：</div>
              <div class="kuang kuang1">
                <a-textarea v-model:value="formData.operationDescription" placeholder="请输入作业要求" />
              </div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">生产标准：</div>
              <div class="kuang  sousuo">
                <a-input v-model="keyword" placeholder="请输入搜索生产标准关键字" type="text" id="" class="ant-input"
                  @change="changeWord" @pressEnter="searchWord" />
                <div class="ss_icon" @click="searchWord">
                  <img class="ss_icon_img" src="/icn_ss.png" alt="">
                </div>
              </div>
              <div class="lb_item_ts">提示：点击生产标准即可展开看全部，点击 “ + ” 即可快捷添加作业要求。</div>
              <div class="">
                <div style="display: flex;justify-content: space-between;align-items: center;"
                  v-for="(item,index) in scbz_arr" :key="item.title">
                  <div class="kuang scbz_item" :class="{scbz_item1: item.more, active: item.selected}" @click="look(index)">
                    {{item.title}}
                  </div>
                  <div class="lb_item_jia" @click="choice(index)" :class="item.selected ? 'lb_item_jia1': ''">
                    <svg class="lb_item_jia_img" xmlns="http://www.w3.org/2000/svg"
                      xmlns:xlink="http://www.w3.org/1999/xlink" width="21" height="21" viewBox="0 0 21 21" fill="none">
                      <path id="并集" fill-rule="evenodd" style="fill:#E5E7EB" opacity="1"
                        d="M0 9L0 12L9 12L9 21L12 21L12 12L21 12L21 9L12 9L12 0L9 0L9 9L0 9Z"></path>
                    </svg>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
          <a-col span="12" style="margin: auto;" v-if="current == 2">
            <div class="lb_item">
              <div class="lb_tit">作业开始时间</div>
              <div class="kuang">
                <a-space direction="vertical">
                  <a-date-picker v-model:value="formData.jobStartTime" valueFormat="YYYY-MM-DD HH:mm:ss" :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" />
                </a-space>
              </div>
              <div class="wxts" v-if="errmsg.indexOf('jobStartTime') > -1">请选择作业开始时间!</div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">计划操作人<span>*</span></div>
              <div class="jhczr">
                <UserSelect v-model:value="formData.jobUsers" :multi="true"/>
              </div>
              <div class="wxts" v-if="errmsg.indexOf('jobUsers') > -1">请选择计划操作人!</div>
            </div>
          </a-col>
        </div>
      </a-col>
    </a-row>
    <template #footer>
      <div class="steps-action">
        <a-button v-if="current > 0" style="margin-right: 8px" @click="prev">上一步</a-button>
        <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
        <a-button v-if="current == steps.length - 1" type="primary" @click="handleSubmit">
          提交
        </a-button>
      </div>
    </template>
    <ClassificationModal @register="registerModal1" @success="handleSuccess"/>
  </BasicModal>
</template>

<script lang="ts" setup>
  import dayjs, { Dayjs } from 'dayjs';
  import { ref, computed, unref, watch, onUnmounted } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { saveOrUpdate } from '../TProductionSchedule.api';
  import { list } from "/@/views/planting-process/productionScheduleTemplate/ProductionScheduleTemplate.api";
  import { defHttp } from "/@/utils/http/axios";
  import UserSelect from '/@/components/Form/src/jeecg/components/userSelect/index.vue'
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue'
  import ApiSelect from '/@/components/Form/src/components/ApiSelect.vue'
  // import JTreeSelect from '/@/components/Form/src/jeecg/components/JTreeSelect.vue'

  import type { SelectProps } from 'ant-design-vue';
  import JSelectMultiple from "@/components/Form/src/jeecg/components/JSelectMultiple.vue";
  import ClassificationModal from './ClassificationModal.vue';
  const options1 = ref<SelectProps['options']>([]);
  const options2 = ref<SelectProps['options']>([]);
  const options3 = ref<SelectProps['options']>([]);
  const plan = ref({});
  const planList = ref([])
  const isInput = ref(false);
  const changeInput = (e: any) => {
    if (e == '') {
      isInput.value = false;
    } else {
      isInput.value = true;
    }
  }
  const getPlan = (params) => {
    return defHttp.get({url: '/growPlan/list', params}).then(res => {
      console.log(res)
      if (res.total) {
        planList.value = res.records
        // plan.value = res.records[0]
        // operateParams.value.associateId =plan.value.product.category
      }
      // options1.value = res
    })
  }
  const getOperate = () => {
    return defHttp.get({url: '/classification/rootList', params: operateParams.value})
  }

  const operateParams = ref({
    pid: '1689815136974086145',
    associateId: '',
    op:"op",
    pageSize: 100
  })

  const getInput = () => {
    defHttp.get({url: '/sys/dict/getDictItems/t_inputs,name,id'}).then(res => {
      options3.value = res
    })
  }

  const getContent = (id, no) => {
    // console.log(id, no)
    if (!isUpdate.value || formData.value.operationContent == '') {
      defHttp.get({url: '/productionSchedule/predict', params: { productionOperation: id.toString(), productNo: no }}).then(res => {
        formData.value.operationContent = res.predict
      }).catch(err => {
        console.warn(err)
      })
    }
  }

  const range = (start : number, end : number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  const disabledDate = (current : Dayjs) => {
    return current && current < dayjs().endOf('day');
  };

  const disabledDateTime = () => {
    return {
      disabledHours: () => range(0, 24).splice(4, 20),
      disabledMinutes: () => range(30, 60),
      disabledSeconds: () => [55, 56],
    };
  };

  const handleChange1 = (value : string) => {
    if (value != null) {
      errmsg.value = errmsg.value.filter(item => item != 'growPlanId')
      getPlan({planId: value})
      formData.value.productionOperation = '';
      formData.value.growPlanProductPlotId ='';
    } else {
      formData.value.growPlanProductPlotId = ''
      plan.value = {};
      planList.value = []
    }
  };
  const handleChange2 = (value : string) => {
    // console.log(value, plan.value.productNo)
    if (value != '') {
      errmsg.value = errmsg.value.filter(item => item != 'productionOperation')
      getContent(value, plan.value.productNo)
    }
  };
  const handleChange3 = (value : string) => {
    if (value != '') {
      errmsg.value = errmsg.value.filter(item => item != 'growPlanProductPlotId')
      planList.value.filter(item => item.id == value).forEach(val => {
        plan.value = val
      })
      operateParams.value.associateId = plan.value.product.category
      formData.value.productionOperation = '';
    }
  };
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);

  // 步骤条配置
  const current = ref<number>(0);
  const next = () => {
    validateForm(true);
  };
  const prev = () => {
    current.value--;
  };

  // 分别展示表单项
  watch(current, (v) => {
    switch (v) {
      case 0:
        break;
      case 1:
        // getInput();
        getProductionStandard('');
        break;
      case 2:
        break;
    }
  })

  const formData = ref({
    id: '',
    growPlanId: '',
    growPlanProductPlotId: '',
    productionOperation: '',
    input: '',
    usageAndDosage: '',
    operationContent: '',
    operationDescription: '',
    jobStartTime: '',
    jobUsers: ''
  })

  const scbz_arr = ref();
  const getProductionStandard = (word : string) => {
    const formData = getFieldsValue();
    if (formData.growPlanId && formData.productionOperation) {
      let params = {}
      if (word) {
        params = {
          keyWord: word
        }
      } else {
        params = {
          growPlanId: formData.growPlanId,
          productionOperation: formData.productionOperation,
          keyWord: word || ''
        }
      }
      defHttp.get({
        url: "/productionStandard/getStandByProductionOperationAndGrowPlan", params: params
      }).then(res => {
        scbz_arr.value = [];
        res.records.map((item: { content: any; }) => {
          scbz_arr.value.push({
            title: item.content,
            selected: false,
            more: false,
          })
        })
      })
    }
  }

  const keyword = ref();
  const changeWord = (e) => {
    keyword.value = e.target.value;
  }
  const searchWord = () => {
    getProductionStandard(keyword.value)
  }

  const choice = (index: string | number) => {
    scbz_arr.value[index].selected = !scbz_arr.value[index].selected
    let content = getFieldsValue().operationDescription || '';
    if (scbz_arr.value[index].selected) {
      content += scbz_arr.value[index].title
    } else {
      content = content.replace(scbz_arr.value[index].title, '');
    }
    setFieldsValue({ operationDescription: content })
  }

  const look = (index: string | number) => {
    scbz_arr.value[index].more = !scbz_arr.value[index].more
  }
  const steps = [
    {
      title: '做什么？',
      description: '选择农事类型',
      content: 'First-content',
    },
    {
      title: '有无投入品？',
      description: '选投入品',
      content: 'Second-content',
    },
    {
      title: '任务分工',
      description: '指派人和时间',
      content: 'Last-content',
    },
  ];

  const cardData = ref([]);
  const pagination = {
    total: 0,
    showQuickJumper: true,
    onChange: (page : number) => {
      pageList({ pageSize: 5, pageNo: page })
    },
    pageSize: 5,
  };

  async function pageList(page) {
    list(page).then(res => {
      cardData.value = res.records;
      pagination.total = res.total;
    })
  }

  const resetFields = () => {
    Object.keys(formData.value).map(key => {
      formData.value[key] = ''
    })
  }

  const setFieldsValue = (data) => {
    // console.log(data)
    Object.keys(formData.value).map(key => {
      if (data.hasOwnProperty(key)) {
        formData.value[key] = data[key]
      }
    })
  }

  const getFieldsValue = () => {
    return formData.value;
  }

  const errmsg = ref([])

  const validateFields = (data: PropertyKey[]) => {
    return new Promise<void>(function(resolve, reject){
      errmsg.value = [];
      data.map((field: string) => {
        if (formData.value.hasOwnProperty(field) && formData.value[field] == '') {
          errmsg.value.push(field)
        }
      })
      if (errmsg.value.length) {
        reject(false);
      } else {
        resolve();
      }
    })
  }

  const validateForm = async (type: boolean) => {
    switch (current.value) {
      case 0:
        validateFields(['growPlanId', 'productionOperation']).then(_res => { type ? current.value++ : current.value--; }).catch(err => { console.log(err) });
        break;
      case 1:
        validateFields([]).then(_res => { type ? current.value++ : current.value--; }).catch(err => { console.log(err) });
        break;
      case 2:
        validateFields(['jobStartTime', 'jobUsers']).then(_res => { type ? current.value++ : current.value--; }).catch(err => { console.log(err) });
        break;
    }
  }

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    if (data && data.record) {
      data.record.growPlanId = data.record.growPlanId.toString();
      data.record.productionOperation = data.record.productionOperation.toString();
    }
    //重置表单
    resetFields();

    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    current.value = data?.current || 0
    if (unref(isUpdate)) {
      //表单赋值
      setFieldsValue({
        ...data.record,
        jobUsers: data.record.jobUsers.join(',')
      });
      await getPlan({planId: data.record.growPlanId})
      handleChange3(data.record.growPlanProductPlotId)
    } else {
      plan.value = {}
      planList.value = []
      console.log(formData.value)
      // pageList({ pageSize: 5, pageNo: 1 })
    }
    // getPlan();
    // getOperate();
  });

  const [registerModal1, {openModal}] = useModal();
  /**
   * 新增农事操作
   */
  async function addOperation() {
    await validateFields(['growPlanId']);
    openModal(true, {
      isUpdate: false,
      record: {
        associateId: plan.value.product.category
      }
    });
  }

  /**
   * 成功回调
   */
  async function handleSuccess({isUpdate, values, expandedArr, changeParent}) {
    // console.log(isUpdate, values, expandedArr, changeParent)
    operateParams.value._t = (new Date()).getTime()
  }

  //表单提交事件
  async function handleSubmit(_v: any) {
    try {
      await validateFields(['jobStartTime', 'jobUsers']);
      let values = getFieldsValue();

      if (typeof values.jobUsers == 'string') {
        values.jobUsers = values.jobUsers.split(',')
      }
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  const beforeClose = () => {
    operateParams.value.associateId = ''
    return true;
  }
</script>

<style lang="less">
  .scbz_item {
    padding: 4px 20px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    color: rgba(0, 0, 0, 0.45);
    width: 90%;
    transition: all 0.5s;

  }

  .lb_tit {
    margin-left: 10px;
  }

  .scbz_item1 {
    height: auto !important;
    white-space: wrap;
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .scbz_item:hover, .scbz_item.active {
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .lb_item {
    margin-bottom: 30px;

    &_ts {
      font-size: 10px;
      color: #FF9233;
      padding: 20px 10px 0px;
    }

    .ant-select-arrow,.lb_tit span {
      color: #FF4D4F;
      margin-right: 10px;
    }

    &_jia {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: #FFF;
      border: 1px solid #E5E7EB;
      // line-height: 40px;
      text-align: center;
      font-size: 1.5rem;
      color: #E5E7EB;
      transition: all 0.5s;
      cursor: pointer;
      position: relative;

      &_img {
        width: 15px;
        height: 15px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    &_jia:hover {
      border: 1px solid #40a9ff;
      box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
    }

    &_jia:hover>&_jia_img path {
      fill: #40a9ff !important;
    }

    &_jia1 {
      transform: rotate(45deg);
    }
  }

  .jhczr {
    margin-top: 6px;
  }

  .lb_item .jhczr span {
    margin-right: 0px;
    color: #333;
  }

  .kuang {
    height: 40px;
    opacity: 1;
    border-radius: 2px;
    background: #FFFFFF;
    border: 1px solid #E5E7EB;
    margin-top: 6px;
  }

  .kuang>.ant-select {
    width: 100% !important;
    height: 100% !important;
  }

  .kuang>.ant-select>.ant-select-selector {
    width: 100% !important;
    height: 100% !important;
    border: none;
  }

  .kuang>.ant-select>.ant-select-selector .ant-select-selection-search-input,
  .kuang>.ant-select>.ant-select-selector .ant-select-selection-overflow,
  .kuang>.ant-select>.ant-select-selector .ant-select-selection-overflow-item{
    height: 100%;
  }

  .kuang>.ant-select>.ant-select-selector>.ant-select-selection-item,
  .kuang>.ant-select>.ant-select-selector .ant-select-selection-placeholder {
    height: 100%;
    line-height: 40px;
  }

  .kuang>.ant-select-multiple .ant-select-selection-item {
    height: 30px;
    line-height: 30px;
  }

  .kuang:hover {
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .kuang .ant-space,
  .kuang .ant-space-item,
  .kuang .ant-picker {
    width: 100% !important;
    height: 100% !important;
    border: none;
  }

  .kuang1 {
    height: 180px;
  }

  .kuang1>.ant-input {
    width: 100%;
    height: 100%;
    border: none;
  }

  .wxts {
    color: #ED6F6F;
    margin-left: 10px;
    font-size: 12px;
    margin-top: 10px;
  }

  .scbz_list {
    display: flex;
    flex-wrap: wrap;

  }

  #scbz_item {
    margin: 5px;
    line-height: 36px;
    padding: 0px 15px;
    background: #fff;
    color: rgba(0, 0, 0, 0.6);
    border: 1px solid #E5E7EB;
    box-sizing: border-box;
    border-radius: 4px;
    cursor: pointer;
    transition: border-color .5s;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  #scbz_item:hover {
    border: 1px solid #40a9ff !important;
    color: #40a9ff !important;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .scbz_item_active {
    border: 1px solid #40a9ff !important;
    color: #40a9ff !important;
  }

  .steps-flow {
    width: 75%;
    margin: 30px auto;
  }

  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%
  }

  :deep(.ant-calendar-picker) {
    width: 100%
  }

  // 步骤条样式
  .steps-content {
    margin-top: 16px;
    // border: 1px dashed #e9e9e9;
    border-radius: 6px;
    // background-color: #fafafa;
    min-height: 200px;
    // text-align: center;
    padding-top: 60px;
    min-height: 500px;
  }

  .steps-action {
    margin-top: 24px;
    text-align: right;
  }

  .sousuo {
    position: relative;

    .ant-input {
      height: 100%;
      border: none;
    }

    .ss_icon {
      position: absolute;
      height: 70%;
      width: 50px;
      top: 50%;
      right: 0;
      bottom: 0;
      border-left: 1px solid #eee;
      transform: translateY(-50%);
      cursor: pointer;
    }

    .ss_icon_img {
      width: 20px;
      height: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  [data-theme='dark'] .steps-content {
    background-color: #2f2f2f;
    border: 1px dashed #404040;
  }

  @media (max-width: 1550px) {
    .steps-flow {
      width: 100%;
      margin: 30px auto;
    }
  }

  @media (max-width: 1366px) {
    .scbz_box>.ant-col-12 {
      max-width: 70%;
    }
  }

  html,
  body {
    font-family: PingFang SC;
  }
</style>
